<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <link rel="stylesheet" href="../lib/swiper-bundle.min.css" />
    <script src="../lib/vue2.js"></script>

    <style>
      #box {
        width: 50%;
        height: 300px;
        background-color: antiquewhite;
        margin: 80px auto;
      }
      .mySwiper {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <!-- 
        主要问题:什么时候初始化轮播图
        1.组件mounted阶段:
            问题:如果数据是异步返回可能会初始化过早,导致没有轮播内容
         
        2.组件updated阶段
            问题:当相关状态改变就会再次初始化,多次创建重复对象
        
        解决方案:使用mounted时给外层组件加上key值关联数据数组,当数组改变时反馈到key值,key值改变就会重新创建一个组件,相当于每次改变数据都会初始化
     -->
    <div id="box">
      <swiper v-if="swiperList.length">
        <swiper-group slot="swiper-group">
          <swiper-item v-for="item in swiperList" :key="item"
            >{{item}}</swiper-item
          >
        </swiper-group>
        <page-item slot="page-item"></page-item>
      </swiper>
    </div>
    <script src="../lib/swiper-bundle.min.js"></script>
    <script>
      // 注册组件swiper
      Vue.component("swiper", {
        template: `<div class="swiper mySwiper">   
            
          <!-- 轮播内容 -->
          <slot name="swiper-group"></slot>
       
        <!-- 分页器 -->
        <slot name="page-item"></slot>
      </div>`,

        mounted() {
          init();
        },
      });
      // 注册组件swiper-group
      Vue.component("swiper-group", {
        template: `<div class="swiper-wrapper">
            <slot></slot>
             </div>`,
      });
      // 注册组件page-item
      Vue.component("page-item", {
        template: ` <div class="swiper-pagination"></div>`,
      });
      //   注册组件swiper-item
      Vue.component("swiper-item", {
        template: `<div class="swiper-slide">
            <slot></slot></div>`,
      });

      new Vue({
        el: "#box",
        data() {
          return {
            swiperList: [],
          };
        },

        // dom挂载
        mounted() {
          // 模拟ajax异步获得数据
          setTimeout(() => {
            this.swiperList = ["1", "2", "3"];
          }, 2000);
          //   init();
        },
      });

      function init() {
        new Swiper(".mySwiper", {
          //     navigation: {
          //   nextEl: ".swiper-button-next",
          //   prevEl: ".swiper-button-prev",
          // },
          pagination: {
            el: ".swiper-pagination",
          },
        });
      }
    </script>
  </body>
</html>
